import {Component, ElementRef, EventEmitter, inject, Input, OnInit, Output, ViewChild, OnChanges, SimpleChanges} from '@angular/core';
import {TodoData} from '../../models/todolists';
import {UserInfo} from '../../models/auth';
import { TodolistsService } from '../../services/todolists.service';

@Component({
  selector: 'app-todolists',
  standalone: false,
  templateUrl: './todolists.component.html',
  styleUrl: './todolists.component.css'
})
export class TodolistsComponent implements OnInit, OnChanges {
  @ViewChild('editInput') editInput!: ElementRef<HTMLDivElement>;
  @Input() todolists!: TodoData[]
  @Input() filterDate!: TodoData[]
  @Input() userInfo!: UserInfo
  @Output() deletedTodo = new EventEmitter()
  private TodolistsService = inject(TodolistsService)
  currentEditId: string = '';
  isAllSelected: boolean = false;
  unFinisdedNum = 0

  ngOnInit() {
    this.updateUnfinishedTodos()
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['todolists'] && !changes['todolists'].firstChange) {
      this.updateUnfinishedTodos();
    }
  }

  updateUnfinishedTodos(ids?: string[], completed?: Boolean): void {
    this.unFinisdedNum =  this.todolists.filter((item) => !item.completed).length
    this.isAllSelected = !this.unFinisdedNum
    if(ids && completed !== undefined){
      this.updateTodoSelect(ids, completed)
    }
  }

  updateAllSelected(){
    const ids: string[] = []
    this.todolists.forEach(item => {
      item.completed = this.isAllSelected;
      ids.push(item._id)
    })
    this.updateUnfinishedTodos(ids, this.isAllSelected)
  }

  updateTodoSelect(id: string[], completed: Boolean): void {
    this.TodolistsService.updateSelectTodos(id, completed).subscribe({
      next: request => {
        // this.loadTodolists();
      },
      error: (error) => {
        console.error('Failed to update todolists:', error);
      }
    })
  }

  deleteTodolist(id: string): void {
    this.TodolistsService.deleteTodo(id).subscribe({
      next: request => {
        this.deletedTodo.emit(id)
        this.filterDate = this.filterDate.filter(item => item._id !== id)
        // this.loadTodolists()
      }
    })
  }

  onEditTodo(id: string): void {
    this.currentEditId = id;
    setTimeout(()=>{
      this.editInput.nativeElement.focus();
    },0)
  }

  upadteTodo(id: string, title: string): void {
    this.currentEditId = '';
    this.TodolistsService.updateTodo(id, title).subscribe({
      next: request => {
        // this.loadTodolists();
      },
      error: (error) => {
        console.error('Failed to update todolists:', error);
      }
    })
  }

}
